package com.nextive.weightlogger.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.nextive.weightlogger.MenuManager;
import com.nextive.weightlogger.R;
import com.nextive.weightlogger.dao.SettingsDao;
import com.nextive.weightlogger.dao.WeightLogDao;
import com.nextive.weightlogger.dto.Settings;
import com.nextive.weightlogger.dto.WeightEntry;

/**
 * Displays the weight entries in the database and lets the user delete entries
 * or pick an entry for edit.
 * 
 * @author Federico Baseggio <fedebaseggio@gmail.com>
 */
public class WeightHistoryActivity extends ListActivity {
	private final String FIELD_DATE = "date";
	private final String FIELD_WEIGHT = "weight";

	private WeightLogDao dao;
	private ListView listView;
	private List<WeightEntry> entries;
	private SettingsDao settingsDao;
	private Settings settings;
	private MenuManager menuManager;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.weight_history);
		
		listView = (ListView)findViewById(android.R.id.list);
		View header = (View) getLayoutInflater().inflate(
				R.layout.weight_history_header, null);
		listView.addHeaderView(header);
		listView.setEmptyView(findViewById(android.R.id.empty));
		
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				WeightHistoryActivity.this.onItemClicked(position - 1);
			}
		});
		
		registerForContextMenu(getListView());
		
		dao = new WeightLogDao(this);
		settingsDao = new SettingsDao(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menuManager = new MenuManager(this);
	    return menuManager.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (menuManager.onOptionsItemSelected(item))
		{
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		
		int index = ((AdapterContextMenuInfo) item.getMenuInfo()).position - 1;

		switch (item.getItemId()) {
		case R.id.history_context_edit:
			editItemAt(index);
			return true;
		case R.id.history_context_delete:
			deleteItemAt(index);
			return true;
		}
		
		return super.onContextItemSelected(item);
		
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.history_list_context, menu);
		int index = ((AdapterContextMenuInfo)menuInfo).position - 1;
		menu.setHeaderTitle(entries.get(index).getDateForDisplay());
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		settings = settingsDao.readSettings();
		entries = dao.readAll();
		populateList();
	}

	/**
	 * Populates the list view with the entries.
	 */
	private void populateList() {
		List<Map<String, String>> adapterEntries = 
			new ArrayList<Map<String, String>>();

		for (WeightEntry entry : entries) {
			Map<String, String> adapterEntry = new HashMap<String, String>();
			adapterEntry.put(FIELD_DATE, entry.getDateForDisplay());
			adapterEntry.put(FIELD_WEIGHT, entry.getWeightForDisplay(settings
					.getUnit()));
			adapterEntries.add(adapterEntry);
		}

		String[] entryKeys = new String[] { FIELD_DATE, FIELD_WEIGHT };
		int[] columnResourceIds = { R.id.weight_history_list_item_date,
				R.id.weight_history_list_item_weight };
		SimpleAdapter adapter = new SimpleAdapter(this, adapterEntries,
				R.layout.weight_history_list_item, entryKeys, 
				columnResourceIds);
		listView.setAdapter(adapter);
	}

	/**
	 * Handles list items clicks.
	 * 
	 * @param index
	 *            The index of the item in the {@link #entries} list.
	 */
	private void onItemClicked(int index)
	{
		editItemAt(index);
	}
	
	/**
	 * Deletes the item at the specified index.
	 * 
	 * @param index
	 *            The index of the item in the {@link #entries} list.
	 */
	private void deleteItemAt(int index)
	{
		Long entryId = entries.get(index).getId();
		dao.delete(entryId);
		entries = dao.readAll();
		populateList();
	}
	
	/**
	 * Launches the {@link LogWeightActivity} activity to edit the weight entry
	 * at the specified index.
	 * 
	 * @param index
	 *            The index of the item in the {@link #entries} list.
	 */
	private void editItemAt(int index)
	{
		Long entryId = entries.get(index).getId();
		
		Intent intent = new Intent(this, LogWeightActivity.class);
		intent.setAction(Intent.ACTION_EDIT);
		intent.putExtra(LogWeightActivity.INTENT_EXTRA_ID, entryId);
		
		startActivity(intent);
	}
}
